module ModuleSaving
    
    use Globals
    
    contains

    ! Save initial steady-state policy functions, value function, and measure
    subroutine SavePolicies_INIT
    
    implicit none
    
    open(1,  file = 'Output/V_init.txt',      status = 'unknown')
    open(2,  file = 'Output/c_pol_init.txt',  status = 'unknown')
    open(3,  file = 'Output/h_pol_init.txt',  status = 'unknown')
    open(4,  file = 'Output/a_pol_init.txt',  status = 'unknown')
    open(5,  file = 'Output/mu_init.txt',  status = 'unknown')
    
    write(1, *) V
    write(2, *) c_pol
    write(3, *) h_pol
    write(4, *) a_pol        
    write(5, *) mu
    
    close(1)
    close(2)
    close(3)
    close(4)
    close(5)
    
    end subroutine SavePolicies_INIT
    
    ! Save prices and aggregates for initial steady state
    subroutine SavePrices_INIT
    
    implicit none
    
    open(1,  file = 'Output/Prices_INIT.txt',      status = 'unknown')
    write(1, *) [mt, r, Kagg, Yagg]
    close(1)    
    
    end subroutine SavePrices_INIT

    ! Save final steady-state policy functions, value function, and measure
    subroutine SavePolicies_LR

    implicit none

    open(1,  file = 'Output/V_lr.txt',      status = 'unknown')
    open(2,  file = 'Output/c_pol_lr.txt',  status = 'unknown')
    open(3,  file = 'Output/h_pol_lr.txt',  status = 'unknown')
    open(4,  file = 'Output/a_pol_lr.txt',  status = 'unknown')
    open(5,  file = 'Output/mu_lr.txt',  status = 'unknown')

    write(1, *) V
    write(2, *) c_pol
    write(3, *) h_pol
    write(4, *) a_pol
    write(5, *) mu

    close(1)
    close(2)
    close(3)
    close(4)
    close(5)

    end subroutine SavePolicies_LR
    
    ! Save prices and aggregates for final steady state
    subroutine SavePrices_LR

    implicit none

    open(1,  file = 'Output/Prices_LR.txt',      status = 'unknown')
    write(1, *) [mt, r, Kagg, Yagg]
    close(1)

    end subroutine SavePrices_LR
    
    ! Save prices and aggregates along the transition
    subroutine SaveAggregates_TR

    implicit none

    open(1,  file = 'Output/Kagg_TR.txt',      status = 'unknown')
    open(2,  file = 'Output/Lagg_TR.txt',      status = 'unknown')
    open(3,  file = 'Output/r_TR.txt',      status = 'unknown')
    open(4,  file = 'Output/mt_TR.txt',      status = 'unknown')

    write(1, *) Kagg_TR
    write(2, *) Lagg_TR
    write(3, *) r_TR
    write(4, *) mt_TR

    close(1); close(2); close(3); close(4);

    end subroutine SaveAggregates_TR

end module ModuleSaving
